package cn.chaos.bio.exercise;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class BioServer {


    public static void main(String[] args) {

        int port = 11111;
        ServerSocket serverSocket = null;

        boolean running = true;
        try {
            serverSocket = new ServerSocket(port);
            while (running && serverSocket != null) {
                final Socket socket = serverSocket.accept();
                Thread thread = new Thread(new Process(socket));
                thread.start();
                System.out.println(thread.getName());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static class Process implements Runnable {

        private Socket socket;

        private Process(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (InputStream in = socket.getInputStream();
                 OutputStream out=socket.getOutputStream();

            ) {

                StringBuilder request = new StringBuilder();
                while (true) {
                    char c = (char) in.read();
                    request.append(c);
                    if (request.length() > 4 && request.substring(request.length() - 4).equals("\r\n\r\n")) {
                        break;
                    }
                }
                System.out.println(request);
                socket.shutdownInput();

                Path file = Paths.get("/Users/chengchao/chaos-notes/pdf-books/spring.html");
                byte[] bytes = Files.readAllBytes(file);
                out.write("HTTP/1.1 200 OK\n".getBytes());
                out.write("Content-Type: text/html; charset=UTF-8\n".getBytes());
                out.write(("Content-Length: "+ (bytes.length) + "\n").getBytes());
                out.write("\n".getBytes());
                out.flush();
                out.write(bytes);
                out.flush();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
